<template>
  <div class="test-cases-container">
    <!-- 左右分栏布局 -->
    <div class="layout-container">
      <!-- 左侧：用例库树形结构 -->
      <div class="left-panel">
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="panel-header">
              <span class="panel-title">用例库</span>
            </div>
          </template>
          
          <!-- 搜索框 -->
          <div class="folder-search">
            <el-input
              v-model="folderSearchKeyword"
              placeholder="输入关键字搜索"
              clearable
              size="small"
              @input="handleFolderSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <!-- 文件夹树 -->
          <div class="folder-tree-container" @contextmenu.prevent="handleTreeContextMenu">
            <el-tree
              ref="folderTreeRef"
              v-loading="foldersLoading"
              :data="folderTreeData"
              :props="treeProps"
              node-key="id"
              :expand-on-click-node="false"
              :highlight-current="true"
              :default-expand-all="false"
              :filter-node-method="filterFolderNode"
              @node-click="handleFolderClick"
              @node-contextmenu="handleFolderContextMenu"
            >
              <template #default="{ node, data }">
                <div 
                  class="tree-node"
                  :data-folder-id="data.id"
                  :draggable="true"
                  @dragstart="handleFolderDragStart($event, data)"
                  @dragover.prevent="handleFolderDragOver($event, data)"
                  @drop="handleFolderDrop($event, data)"
                  @dragend="handleFolderDragEnd"
                >
                  <span class="node-label">
                    <el-icon class="node-icon"><Folder /></el-icon>
                    {{ node.label }}
                  </span>
                  <span class="node-count" v-if="data.test_case_count > 0">
                    ({{ data.test_case_count }})
                  </span>
                  <div class="node-actions" @click.stop>
                    <el-dropdown trigger="click" @command="(cmd) => handleFolderAction(cmd, data)">
                      <el-button type="text" size="small" class="action-btn">
                        <el-icon><MoreFilled /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="add-child">
                            <el-icon><Plus /></el-icon>
                            添加子文件夹
                          </el-dropdown-item>
                          <el-dropdown-item command="add-case">
                            <el-icon><Plus /></el-icon>
                            添加测试用例
                          </el-dropdown-item>
                          <el-dropdown-item command="edit">
                            <el-icon><Edit /></el-icon>
                            编辑
                          </el-dropdown-item>
                          <el-dropdown-item command="delete" divided>
                            <el-icon><Delete /></el-icon>
                            删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </template>
            </el-tree>
            
            <div v-if="!foldersLoading && folderTreeData.length === 0" class="empty-state">
              <el-empty description="暂无文件夹" :image-size="80">
                <el-button 
                  v-if="hasPermission('test_case:create')"
                  type="primary" 
                  size="small"
                  @click="() => handleCreateFolder()"
                >
                  新建文件夹
                </el-button>
              </el-empty>
            </div>
          </div>
          
          <!-- 底部设置按钮 -->
          <div class="folder-footer">
            <el-button
              v-if="hasPermission('test_case:create')"
              type="primary"
              size="small"
              text
              @click="() => handleCreateFolder()"
            >
              <el-icon><Plus /></el-icon>
              新建文件夹
            </el-button>
            <el-button
              size="small"
              text
              @click="handleFolderSettings"
            >
              <el-icon><Setting /></el-icon>
              设置
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 右侧：测试用例筛选和列表 -->
      <div class="right-panel">
        <!-- 页面头部 -->
        <div class="page-header">
          <div class="header-left">
            <h2 class="page-title">测试用例管理</h2>
            <p class="page-description">管理项目中的测试用例，跟踪测试执行进度</p>
          </div>
          <div class="header-right">
            <el-button 
              type="primary" 
              @click="handleCreate"
              v-if="hasPermission('test_case:create')"
            >
              <el-icon><Plus /></el-icon>
              新建测试用例
            </el-button>
          </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <div class="filter-section">
          <el-card shadow="never">
        <div class="filter-row">
          <div class="filter-left">
            <el-input
              v-model="filterForm.search"
              placeholder="搜索测试用例标题、描述..."
              clearable
              style="width: 300px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleResetFilter">重置</el-button>
          </div>
          <div class="filter-right">
            <el-button 
              text 
              @click="showAdvancedFilter = !showAdvancedFilter"
            >
              高级筛选
              <el-icon><ArrowDown v-if="!showAdvancedFilter" /><ArrowUp v-else /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 高级筛选 -->
        <div v-show="showAdvancedFilter" class="advanced-filter">
          <el-row :gutter="16">
            <el-col :span="6">
              <el-select
                v-model="filterForm.status"
                placeholder="选择状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in testCaseStatusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="filterForm.priority"
                placeholder="选择优先级"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in testCasePriorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="filterForm.test_case_type"
                placeholder="选择测试类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in TEST_CASE_TYPE_OPTIONS"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="filterForm.assignee_id"
                placeholder="选择负责人"
                clearable
                filterable
                style="width: 100%"
                :loading="usersLoading"
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <div style="display: flex; align-items: center; gap: 8px;">
                    <span>{{ user.name }}</span>
                    <span v-if="user.username" style="color: #909399; font-size: 12px;">
                      ({{ user.username }})
                    </span>
                  </div>
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="16" style="margin-top: 16px;">
            <el-col :span="6">
              <el-select
                v-model="filterForm.creator_id"
                placeholder="选择创建人"
                clearable
                filterable
                style="width: 100%"
                :loading="usersLoading"
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                  <div style="display: flex; align-items: center; gap: 8px;">
                    <span>{{ user.name }}</span>
                    <span v-if="user.username" style="color: #909399; font-size: 12px;">
                      ({{ user.username }})
                    </span>
                  </div>
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="9">
              <el-date-picker
                v-model="createdDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="创建开始日期"
                end-placeholder="创建结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
              />
            </el-col>
            <el-col :span="9">
              <el-date-picker
                v-model="updatedDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="更新开始日期"
                end-placeholder="更新结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
              />
            </el-col>
          </el-row>
          </div>
          </el-card>
        </div>

        <!-- 测试用例列表 -->
        <div class="table-section">
          <el-card shadow="never">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="testCases"
          @sort-change="handleSortChange"
          @row-contextmenu="handleTestCaseContextMenu"
          stripe
          style="width: 100%"
          row-key="id"
        >
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div 
                class="test-case-row"
                :draggable="true"
                @dragstart="handleTestCaseDragStart($event, row)"
                @dragend="handleTestCaseDragEnd"
              >
                <el-link 
                  type="primary" 
                  @click="handleView(row)"
                  :underline="false"
                >
                  {{ row.title }}
                </el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="120">
            <template #default="{ row }">
              <el-tag size="small">{{ getTestCaseTypeLabel(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="100">
            <template #default="{ row }">
              <el-tag size="small" type="info">{{ getTestCaseCategoryLabel(row.category) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag 
                v-if="row.status"
                :color="getTestCaseStatusColor(row.status)"
                size="small"
                effect="dark"
              >
                {{ getTestCaseStatusLabel(row.status) }}
              </el-tag>
              <span v-else class="text-placeholder">未设置</span>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
              <el-tag 
                v-if="row.priority"
                :color="getTestCasePriorityColor(row.priority)"
                size="small"
                effect="dark"
              >
                {{ getTestCasePriorityLabel(row.priority) }}
              </el-tag>
              <span v-else class="text-placeholder">未设置</span>
            </template>
          </el-table-column>
          <el-table-column prop="assignee_name" label="负责人" width="120">
            <template #default="{ row }">
              <span v-if="row.assignee_name">{{ row.assignee_name }}</span>
              <span v-else class="text-placeholder">未分配</span>
            </template>
          </el-table-column>
          <el-table-column prop="creator_name" label="创建人" width="120">
            <template #default="{ row }">
              <span v-if="row.creator_name">{{ row.creator_name }}</span>
              <span v-else class="text-placeholder">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="150" sortable="custom" align="left" class-name="time-column">
            <template #default="{ row }">
              <div class="time-cell">{{ formatDateTime(row.created_at) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="updated_at" label="更新时间" width="150" sortable="custom" align="left" class-name="time-column">
            <template #default="{ row }">
              <div class="time-cell">{{ formatDateTime(row.updated_at) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="execution_count" label="执行次数" width="100" />
          <el-table-column prop="last_execution_result" label="最后结果" width="100">
            <template #default="{ row }">
              <el-tag 
                v-if="row.last_execution_result"
                :type="getExecutionResultType(row.last_execution_result)"
                size="small"
              >
                {{ getExecutionResultLabel(row.last_execution_result) }}
              </el-tag>
              <span v-else class="text-placeholder">未执行</span>
            </template>
          </el-table-column>
          <el-table-column prop="pass_rate" label="通过率" width="100">
            <template #default="{ row }">
              <span v-if="row.pass_rate !== null && row.pass_rate !== undefined">
                {{ row.pass_rate.toFixed(1) }}%
              </span>
              <span v-else class="text-placeholder">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="project_name" label="所属项目" width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link 
                v-if="row.project_id && row.project_name"
                type="primary" 
                @click="handleViewProject(row.project_id)"
                :underline="false"
              >
                {{ row.project_name }}
              </el-link>
              <span v-else class="text-placeholder">未关联</span>
            </template>
          </el-table-column>
          <el-table-column prop="requirement_name" label="关联需求" width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link 
                v-if="row.requirement_id && row.requirement_name"
                type="primary" 
                @click="handleViewRequirement(row.requirement_id)"
                :underline="false"
              >
                {{ row.requirement_name }}
              </el-link>
              <span v-else class="text-placeholder">未关联</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="handleView(row)"
              >
                查看
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="handleEdit(row)"
                v-if="canEditTestCase(row)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                text 
                @click="handleDelete(row)"
                v-if="canDeleteTestCase(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div
      v-if="contextMenuVisible"
      class="context-menu"
      :style="{ left: contextMenuPosition.x + 'px', top: contextMenuPosition.y + 'px' }"
      @click.stop
    >
      <template v-if="contextMenuTarget === 'folder'">
        <div class="context-menu-item" @click="handleContextMenuAction('add-child')">
          <el-icon><Plus /></el-icon>
          <span>添加子文件夹</span>
        </div>
        <div class="context-menu-item" @click="handleContextMenuAction('add-case')">
          <el-icon><Plus /></el-icon>
          <span>添加测试用例</span>
        </div>
        <div class="context-menu-item" @click="handleContextMenuAction('edit')">
          <el-icon><Edit /></el-icon>
          <span>编辑</span>
        </div>
        <div class="context-menu-divider"></div>
        <div class="context-menu-item" @click="handleContextMenuAction('delete')">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </div>
      </template>
      <template v-else-if="contextMenuTarget === 'testcase'">
        <div class="context-menu-item" @click="handleContextMenuAction('view')">
          <el-icon><View /></el-icon>
          <span>查看</span>
        </div>
        <div class="context-menu-item" @click="handleContextMenuAction('edit')">
          <el-icon><Edit /></el-icon>
          <span>编辑</span>
        </div>
        <div class="context-menu-item" @click="handleContextMenuAction('copy')">
          <el-icon><CopyDocument /></el-icon>
          <span>复制</span>
        </div>
        <div class="context-menu-divider"></div>
        <div class="context-menu-item" @click="handleContextMenuAction('delete')">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </div>
      </template>
    </div>

    <!-- 测试用例创建对话框 -->
    <TestCaseCreateDialog
      v-model="createDialogVisible"
      :project-id="filterForm.project_id || undefined"
      :folder-id="selectedFolderId || undefined"
      @success="handleTestCaseCreated"
    />
    
    <!-- 测试用例查看对话框 -->
    <TestCaseViewDialog
      v-model="viewDialogVisible"
      :test-case-id="selectedTestCaseId"
      @edit="handleEditFromView"
    />
    
    <!-- 测试用例编辑对话框 -->
    <TestCaseEditDialog
      v-model="editDialogVisible"
      :test-case-id="selectedTestCaseId"
      @success="handleTestCaseUpdated"
    />

    <!-- 文件夹创建/编辑对话框 -->
    <el-dialog
      v-model="folderDialogVisible"
      :title="folderDialogMode === 'create' ? '新建文件夹' : '编辑文件夹'"
      width="600px"
      @close="handleFolderDialogClose"
    >
      <el-form :model="folderForm" :rules="folderFormRules" ref="folderFormRef" label-width="100px">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="文件夹描述" prop="description">
          <el-input
            v-model="folderForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文件夹描述"
          />
        </el-form-item>
        <el-form-item label="所属项目" prop="project_id">
          <el-select
            v-model="folderForm.project_id"
            placeholder="选择项目"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="project in projectOptions"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="父文件夹" prop="parent_id">
          <el-select
            v-model="folderForm.parent_id"
            placeholder="选择父文件夹（可选）"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="folder in flatFolderList"
              :key="folder.id"
              :label="folder.name"
              :value="folder.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="folderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveFolder" :loading="folderSaving">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  ArrowDown, 
  ArrowUp, 
  Folder,
  MoreFilled,
  Edit,
  Delete,
  View,
  CopyDocument,
  Setting
} from '@element-plus/icons-vue'

import { 
  getTestCases, 
  deleteTestCase,
  updateTestCase,
  getTestCaseFolders,
  createTestCaseFolder,
  updateTestCaseFolder,
  deleteTestCaseFolder,
  type TestCase,
  type TestCaseFilter,
  type TestCaseFolder,
  type TestCaseFolderCreate,
  type TestCaseFolderUpdate
} from '@/api/test-case'
import { useProjectStore } from '@/stores/project'
import { getUsers } from '@/api/user'
import { useRouter } from 'vue-router'
import { usePermission } from '@/hooks/usePermission'
import { formatDateTime } from '@/utils/date'
import { 
  getTestCaseTypeLabel,
  getTestCaseCategoryLabel,
  getExecutionResultLabel,
  getExecutionResultType,
  TEST_CASE_TYPE_OPTIONS,
  TEST_CASE_FILTER_DEFAULTS
} from '@/types/test-case'
import { useTestCaseStates } from '@/composables/useTestCaseStates'
import { useTestCasePriorities } from '@/composables/useTestCasePriorities'
import { useUserStore } from '@/stores/user'
import { useStateStore } from '@/stores/state'
import { ModuleType } from '@/types/state'
import TestCaseCreateDialog from '@/components/test-case/TestCaseCreateDialog.vue'
import TestCaseEditDialog from '@/components/test-case/TestCaseEditDialog.vue'
import TestCaseViewDialog from '@/components/test-case/TestCaseViewDialog.vue'

const router = useRouter()
const route = useRoute()
const { hasPermission } = usePermission()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const testCases = ref<TestCase[]>([])
const showAdvancedFilter = ref(false)

// 左侧面板数据
const folderTreeRef = ref()
const folderTreeData = ref<any[]>([])
const foldersLoading = ref(false)
const selectedFolderId = ref<string>('')
const folderSearchKeyword = ref<string>('')
const treeProps = {
  children: 'children',
  label: 'name'
}

// 文件夹对话框
const folderDialogVisible = ref(false)
const folderDialogMode = ref<'create' | 'edit'>('create')
const folderFormRef = ref()
const folderSaving = ref(false)
const folderForm = reactive({
  name: '',
  description: '',
  parent_id: undefined as string | undefined,
  project_id: '',
  sort_order: 0
})
const folderFormRules = {
  name: [{ required: true, message: '请输入文件夹名称', trigger: 'blur' }],
  project_id: [{ required: true, message: '请选择项目', trigger: 'change' }]
}

// 扁平化的文件夹列表（用于父文件夹选择）
const flatFolderList = computed(() => {
  const flatten = (folders: any[], result: any[] = []): any[] => {
    folders.forEach(folder => {
      result.push(folder)
      if (folder.children && folder.children.length > 0) {
        flatten(folder.children, result)
      }
    })
    return result
  }
  return flatten(folderTreeData.value)
})

// 日期范围筛选
const createdDateRange = ref<[string, string] | null>(null)
const updatedDateRange = ref<[string, string] | null>(null)

// 筛选表单
const filterForm = reactive<TestCaseFilter>({
  ...TEST_CASE_FILTER_DEFAULTS,
  search: '',
  project_id: '',
  status: undefined,
  priority: undefined,
  test_case_type: undefined,
  assignee_id: undefined,
  creator_id: undefined
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 选项数据
const projectOptions = ref<Array<{ id: string; name: string }>>([])
const userOptions = ref<Array<{ id: string; name: string; username?: string }>>([])
const usersLoading = ref(false)

// 弹窗状态
const createDialogVisible = ref(false)
const editDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const selectedTestCaseId = ref<string>('')

// 右键菜单状态
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const contextMenuTarget = ref<'folder' | 'testcase' | null>(null)
const contextMenuData = ref<any>(null)

// 拖拽状态
const draggingTestCase = ref<TestCase | null>(null)

// 使用动态状态管理获取测试用例状态选项
const { statusOptions: testCaseStatusOptionsFromComposable, loadStates: loadTestCaseStates, getStateName, getStateColor } = useTestCaseStates()
const { priorityOptions: testCasePriorityOptionsFromComposable, fetchPriorities: fetchTestCasePriorities, getPriorityName, getPriorityColor } = useTestCasePriorities()

// 计算属性
const testCaseStatusOptions = computed(() => {
  const options = testCaseStatusOptionsFromComposable.value
  if (!Array.isArray(options) || options.length === 0) {
    console.warn('测试用例状态选项为空，可能需要等待数据加载')
  }
  return options || []
})
const testCasePriorityOptions = computed(() => {
  const options = testCasePriorityOptionsFromComposable.value
  if (!Array.isArray(options) || options.length === 0) {
    console.warn('测试用例优先级选项为空，可能需要等待数据加载')
  }
  return options || []
})

// 状态相关辅助函数（使用动态数据）
const getTestCaseStatusLabel = (value?: string) => {
  if (!value) return '未设置'
  try {
    const label = getStateName(value)
    // 如果返回的是原始值（说明状态未找到），返回原始值
    return label === value ? value : label
  } catch {
    return value || '未设置'
  }
}

const getTestCaseStatusColor = (value?: string) => {
  if (!value) return '#909399'
  try {
    return getStateColor(value)
  } catch {
    return '#909399'
  }
}

// 优先级相关辅助函数（使用动态数据）
const getTestCasePriorityLabel = (value?: string) => {
  if (!value) return '未知'
  return getPriorityName(value)
}

const getTestCasePriorityColor = (value?: string) => {
  if (!value) return '#909399'
  return getPriorityColor(value)
}

const getCurrentUserId = () => {
  return userStore.userInfo?.id || ''
}

const canEditTestCase = (testCase: TestCase) => {
  return hasPermission('test_case:update') || 
         hasPermission('*') ||
         testCase.creator_id === getCurrentUserId() ||
         testCase.assignee_id === getCurrentUserId()
}

const canDeleteTestCase = (testCase: TestCase) => {
  return hasPermission('test_case:delete') || 
         hasPermission('*') ||
         testCase.creator_id === getCurrentUserId()
}

// 加载数据
const loadTestCases = async () => {
  loading.value = true
  try {
    const params: any = {
      ...filterForm,
      // 如果选择了文件夹，则只显示该文件夹中的用例；否则显示所有用例（根据项目筛选）
      folder_id: selectedFolderId.value || filterForm.folder_id || undefined,
      // 如果选择了文件夹，移除project_id筛选；否则保留project_id筛选
      project_id: selectedFolderId.value ? undefined : (filterForm.project_id || undefined),
      skip: (pagination.page - 1) * pagination.size,
      limit: pagination.size
    }
    
    // 处理创建时间范围
    if (createdDateRange.value && createdDateRange.value.length === 2) {
      params.created_start = createdDateRange.value[0]
      params.created_end = createdDateRange.value[1]
    }
    
    // 处理更新时间范围
    if (updatedDateRange.value && updatedDateRange.value.length === 2) {
      params.updated_start = updatedDateRange.value[0]
      params.updated_end = updatedDateRange.value[1]
    }
    
    const result = await getTestCases(params)
    testCases.value = result.items || []
    pagination.total = result.total || 0
    pagination.page = result.page || 1
    pagination.size = result.size || 20
  } catch (error: any) {
    console.error('加载测试用例失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '加载测试用例失败'
    ElMessage.error(errorMessage)
    testCases.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const projectStore = useProjectStore()

// 加载项目列表
const loadProjects = async () => {
  try {
    console.log('开始加载项目列表...')
    const projects = await projectStore.fetchProjects()
    console.log('项目数据:', projects)
    
    if (Array.isArray(projects) && projects.length > 0) {
      const mappedProjects = projects.map((p: any) => {
        const id = p.value || p.id || String(p._id || '')
        const name = p.label || p.name || ''
        return { id, name }
      }).filter(p => p.id && p.name)
      
      projectOptions.value = mappedProjects
      console.log('项目选项已更新，数量:', mappedProjects.length)
    } else {
      projectOptions.value = []
      console.warn('项目列表为空或格式不正确:', projects)
    }
  } catch (error: any) {
    console.error('加载项目列表失败:', error)
    ElMessage.error(`加载项目列表失败: ${error.message || '未知错误'}`)
    projectOptions.value = []
  }
}

// 加载用户列表（带缓存检查，避免重复加载）
const loadUsers = async () => {
  // 如果已有数据，直接返回
  if (userOptions.value.length > 0) {
    return
  }
  
  // 如果正在加载，等待加载完成
  if (usersLoading.value) {
    return
  }
  
  usersLoading.value = true
  try {
    const result = await getUsers({ page: 1, size: 100 })
    if (result && typeof result === 'object' && 'items' in result && Array.isArray(result.items)) {
      userOptions.value = result.items.map((u: any) => ({
        id: u.id || u._id,
        name: u.name || u.username || '',
        username: u.username || ''
      }))
    } else if (Array.isArray(result)) {
      userOptions.value = result.map((u: any) => ({
        id: u.id || u._id,
        name: u.name || u.username || '',
        username: u.username || ''
      }))
    } else {
      userOptions.value = []
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    userOptions.value = []
  } finally {
    usersLoading.value = false
  }
}

// 加载文件夹树
const loadFolders = async (projectId?: string) => {
  foldersLoading.value = true
  try {
    const params: any = {
      tree: true
    }
    if (projectId) {
      params.project_id = projectId
    }
    
    const response = await getTestCaseFolders(params)
    
    if (response && response.success && response.data) {
      const data = response.data
      if (Array.isArray(data)) {
        folderTreeData.value = data
      } else if (data && typeof data === 'object' && 'items' in data && Array.isArray((data as any).items)) {
        folderTreeData.value = (data as any).items
      } else {
        folderTreeData.value = []
      }
    } else {
      folderTreeData.value = []
    }
  } catch (error: any) {
    console.error('加载文件夹树失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '加载文件夹树失败'
    ElMessage.error(errorMessage)
    folderTreeData.value = []
  } finally {
    foldersLoading.value = false
  }
}

// 文件夹搜索过滤
const filterFolderNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.toLowerCase().includes(value.toLowerCase())
}

// 监听搜索关键词变化
const handleFolderSearch = () => {
  if (folderTreeRef.value) {
    folderTreeRef.value.filter(folderSearchKeyword.value)
  }
}

// 文件夹点击处理
const handleFolderClick = (data: any) => {
  selectedFolderId.value = data.id
  filterForm.folder_id = data.id
  pagination.page = 1
  loadTestCases()
}

// 文件夹操作处理
const handleFolderAction = (command: string, data: any) => {
  if (command === 'add-child') {
    handleCreateFolder(data.id)
  } else if (command === 'add-case') {
    // 选中该文件夹，然后创建用例
    selectedFolderId.value = data.id
    filterForm.folder_id = data.id
    handleCreate()
  } else if (command === 'edit') {
    handleEditFolder(data)
  } else if (command === 'delete') {
    handleDeleteFolder(data)
  }
}

// 右键菜单处理
const handleFolderContextMenu = (event: MouseEvent, data: any) => {
  contextMenuVisible.value = true
  contextMenuPosition.value = { x: event.clientX, y: event.clientY }
  contextMenuTarget.value = 'folder'
  contextMenuData.value = data
}

const handleTestCaseContextMenu = (row: TestCase, _column: any, event: MouseEvent) => {
  contextMenuVisible.value = true
  contextMenuPosition.value = { x: event.clientX, y: event.clientY }
  contextMenuTarget.value = 'testcase'
  contextMenuData.value = row
}

const handleTreeContextMenu = (_event: MouseEvent) => {
  // 空白区域的右键菜单
  contextMenuVisible.value = false
}

const handleContextMenuAction = (action: string) => {
  contextMenuVisible.value = false
  if (contextMenuTarget.value === 'folder' && contextMenuData.value) {
    handleFolderAction(action, contextMenuData.value)
  } else if (contextMenuTarget.value === 'testcase' && contextMenuData.value) {
    if (action === 'view') {
      handleView(contextMenuData.value)
    } else if (action === 'edit') {
      handleEdit(contextMenuData.value)
    } else if (action === 'delete') {
      handleDelete(contextMenuData.value)
    } else if (action === 'copy') {
      // TODO: 实现复制功能
      ElMessage.info('复制功能待实现')
    }
  }
}

// 点击其他地方关闭右键菜单
const handleClickOutside = () => {
  contextMenuVisible.value = false
}

// 拖拽处理 - 套件
const handleFolderDragStart = (event: DragEvent, data: any) => {
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('folder-id', data.id)
    event.dataTransfer.setData('drag-type', 'folder')
  }
}

const handleFolderDragOver = (event: DragEvent, _data: any) => {
  event.preventDefault()
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }
  // 添加视觉反馈
  const target = event.currentTarget as HTMLElement
  if (target) {
    target.classList.add('drag-over')
  }
}

const handleFolderDrop = async (event: DragEvent, targetFolder: any) => {
  event.preventDefault()
  const target = event.currentTarget as HTMLElement
  if (target) {
    target.classList.remove('drag-over')
  }
  
  if (!event.dataTransfer) return
  
  const dragType = event.dataTransfer.getData('drag-type')
  
  if (dragType === 'testcase') {
    // 将测试用例移动到文件夹
    const testCaseId = event.dataTransfer.getData('test-case-id')
    if (testCaseId && draggingTestCase.value) {
      try {
        await updateTestCase(testCaseId, {
          folder_id: targetFolder.id
        })
        ElMessage.success('测试用例已移动到文件夹')
        await loadTestCases()
        await loadFolders()
      } catch (error: any) {
        ElMessage.error(error.message || '移动失败')
      }
    }
  } else if (dragType === 'folder') {
    // 移动文件夹到另一个文件夹下（作为子文件夹）
    const sourceFolderId = event.dataTransfer.getData('folder-id')
    if (sourceFolderId && sourceFolderId !== targetFolder.id) {
      try {
        await updateTestCaseFolder(sourceFolderId, {
          parent_id: targetFolder.id
        })
        ElMessage.success('文件夹已移动')
        await loadFolders()
      } catch (error: any) {
        ElMessage.error(error.message || '移动失败')
      }
    }
  }
}

const handleFolderDragEnd = (event: DragEvent) => {
  const target = event.currentTarget as HTMLElement
  if (target) {
    target.classList.remove('drag-over')
  }
}

// 拖拽处理 - 测试用例
const handleTestCaseDragStart = (event: DragEvent, testCase: TestCase) => {
  draggingTestCase.value = testCase
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('test-case-id', testCase.id)
    event.dataTransfer.setData('drag-type', 'testcase')
  }
}

const handleTestCaseDragEnd = () => {
  draggingTestCase.value = null
}

// 创建文件夹
const handleCreateFolder = (parentId?: string) => {
  folderDialogMode.value = 'create'
  folderForm.name = ''
  folderForm.description = ''
  folderForm.project_id = filterForm.project_id || ''
  folderForm.parent_id = parentId || undefined
  folderForm.sort_order = 0
  folderDialogVisible.value = true
}

// 编辑文件夹
const handleEditFolder = (folder: TestCaseFolder) => {
  folderDialogMode.value = 'edit'
  folderForm.name = folder.name
  folderForm.description = folder.description || ''
  folderForm.project_id = folder.project_id || filterForm.project_id || ''
  folderForm.parent_id = folder.parent_id || undefined
  folderForm.sort_order = folder.sort_order || 0
  folderDialogVisible.value = true
}

// 保存文件夹
const handleSaveFolder = async () => {
  if (!folderFormRef.value) return
  
  try {
    await folderFormRef.value.validate()
    folderSaving.value = true
    
    if (folderDialogMode.value === 'create') {
      await createTestCaseFolder(folderForm as TestCaseFolderCreate)
      ElMessage.success('创建文件夹成功')
      await loadFolders(folderForm.project_id)
    } else {
      // 编辑模式需要folder id，这里需要从folderForm中获取或从选中的文件夹获取
      const folderId = selectedFolderId.value
      if (!folderId) {
        ElMessage.error('无法确定要更新的文件夹')
        return
      }
      const updateData: TestCaseFolderUpdate = {
        name: folderForm.name,
        description: folderForm.description,
        project_id: folderForm.project_id,
        parent_id: folderForm.parent_id,
        sort_order: folderForm.sort_order
      }
      await updateTestCaseFolder(folderId, updateData)
      ElMessage.success('更新文件夹成功')
      await loadFolders(folderForm.project_id)
    }
    
    folderDialogVisible.value = false
  } catch (error: any) {
    if (error !== false) {
      console.error('保存文件夹失败:', error)
      const errorMessage = error?.response?.data?.message || error?.message || '保存失败'
      ElMessage.error(errorMessage)
    }
  } finally {
    folderSaving.value = false
  }
}

// 删除文件夹
const handleDeleteFolder = async (folder: TestCaseFolder) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件夹 "${folder.name}" 吗？`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    await deleteTestCaseFolder(folder.id)
    ElMessage.success('删除成功')
    
    if (selectedFolderId.value === folder.id) {
      selectedFolderId.value = ''
      filterForm.folder_id = undefined
    }
    
    await loadFolders()
    loadTestCases()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除文件夹失败:', error)
      const errorMessage = error?.response?.data?.message || error?.message || '删除失败'
      ElMessage.error(errorMessage)
    }
  }
}

// 文件夹对话框关闭
const handleFolderDialogClose = () => {
  folderFormRef.value?.resetFields()
}

// 文件夹设置
const handleFolderSettings = () => {
  ElMessage.info('文件夹设置功能待开发')
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadTestCases()
}

// 重置筛选
const handleResetFilter = () => {
  Object.assign(filterForm, {
    ...TEST_CASE_FILTER_DEFAULTS,
    search: '',
    // 保留project_id，因为左侧面板需要使用
    // project_id: '',  // 不重置项目ID
    status: undefined,
    priority: undefined,
    test_case_type: undefined,
    assignee_id: undefined,
    creator_id: undefined,
    // 不清空test_suite_id，因为用例数据从套件中来
    // test_suite_id: undefined,  // 不重置套件ID
  })
  createdDateRange.value = null
  updatedDateRange.value = null
  // 不清空左侧面板的数据
  // versionOptions.value = []
  // selectedVersionId.value = ''
  // suiteTreeData.value = []
  // selectedSuiteId.value = ''
  handleSearch()
}

// 查看项目
const handleViewProject = (projectId: string) => {
  router.push(`/projects/${projectId}`)
}

// 查看需求
const handleViewRequirement = (requirementId: string) => {
  // 可以跳转到需求详情页面，或者打开需求弹窗
  router.push(`/requirements?requirement_id=${requirementId}`)
}

// 查看版本

// 排序
const handleSortChange = ({ prop, order }: any) => {
  if (prop) {
    filterForm.sort_by = prop
    filterForm.sort_order = order === 'ascending' ? 'asc' : 'desc'
    loadTestCases()
  }
}

// 分页
const handleSizeChange = () => {
  loadTestCases()
}

const handleCurrentChange = () => {
  loadTestCases()
}

// 创建 - 自动关联到当前选中的套件
const handleCreate = () => {
  createDialogVisible.value = true
}

// 创建用例成功回调 - 如果有关联文件夹，需要更新文件夹树
const handleTestCaseCreated = async () => {
  await loadTestCases()
  // 如果当前选中了文件夹，刷新文件夹树以更新用例数量
  if (selectedFolderId.value) {
    await loadFolders()
  }
}

// 查看
const handleView = (testCase: TestCase) => {
  selectedTestCaseId.value = testCase.id
  viewDialogVisible.value = true
}

// 编辑
const handleEdit = (testCase: TestCase) => {
  selectedTestCaseId.value = testCase.id
  editDialogVisible.value = true
}

// 编辑回调（从查看弹窗触发）
const handleEditFromView = () => {
  viewDialogVisible.value = false
  editDialogVisible.value = true
}

const handleTestCaseUpdated = async () => {
  await loadTestCases()
  // 如果当前选中了文件夹，刷新文件夹树以更新用例数量
  if (selectedFolderId.value) {
    await loadFolders()
  }
}

// 删除
const handleDelete = async (testCase: TestCase) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除测试用例 "${testCase.title}" 吗？`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    await deleteTestCase(testCase.id)
    ElMessage.success('删除成功')
    loadTestCases()
    // 如果当前选中了文件夹，刷新文件夹树以更新用例数量
    if (selectedFolderId.value) {
      await loadFolders()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除测试用例失败:', error)
      const errorMessage = error?.response?.data?.message || error?.message || '删除失败'
      ElMessage.error(errorMessage)
    }
  }
}

// 初始化
onMounted(async () => {
  // 并行加载所有基础数据（只加载一次）
  try {
    // 检查数据是否已加载，避免重复调用
    const statusAlreadyLoaded = testCaseStatusOptions.value.length > 0
    const priorityAlreadyLoaded = testCasePriorityOptions.value.length > 0
    const projectsAlreadyLoaded = projectOptions.value.length > 0
    const usersAlreadyLoaded = userOptions.value.length > 0
    
    const loadPromises: Promise<any>[] = []
    
    // 只在数据未加载时才发起请求
    if (!statusAlreadyLoaded) {
      loadPromises.push(
        loadTestCaseStates().catch(err => {
          console.error('加载测试用例状态失败:', err)
        })
      )
    }
    
    if (!priorityAlreadyLoaded) {
      loadPromises.push(
        fetchTestCasePriorities().catch(err => {
          console.error('加载测试用例优先级失败:', err)
        })
      )
    }
    
    if (!projectsAlreadyLoaded) {
      loadPromises.push(
        loadProjects().catch(err => {
          console.error('加载项目列表失败:', err)
        })
      )
    }
    
    if (!usersAlreadyLoaded) {
      loadPromises.push(
        loadUsers().catch(err => {
          console.error('加载用户列表失败:', err)
        })
      )
    }
    
    // 并行执行所有需要加载的请求
    if (loadPromises.length > 0) {
      await Promise.allSettled(loadPromises)
      // 等待一个tick，确保响应式数据更新
      await nextTick()
    }
    
    // 验证数据是否加载成功（只在确实为空时才尝试强制刷新）
    const finalStatusCount = testCaseStatusOptions.value.length
    const finalPriorityCount = testCasePriorityOptions.value.length
    const finalProjectCount = projectOptions.value.length
    
    // 如果数据仍然为空，才尝试强制刷新（这种情况应该很少见）
    if (finalStatusCount === 0 && !statusAlreadyLoaded) {
      console.warn('状态选项为空，尝试强制刷新')
      try {
        const stateStore = useStateStore()
        await stateStore.fetchModuleStates(ModuleType.TEST_CASE, true)
      } catch (err) {
        console.error('强制刷新状态失败:', err)
      }
    }
    if (finalPriorityCount === 0 && !priorityAlreadyLoaded) {
      console.warn('优先级选项为空，尝试强制刷新')
      try {
        await fetchTestCasePriorities(true)
      } catch (err) {
        console.error('强制刷新优先级失败:', err)
      }
    }
    if (finalProjectCount === 0 && !projectsAlreadyLoaded) {
      console.warn('项目选项为空，尝试强制刷新')
      try {
        await projectStore.fetchProjects(undefined, true)
        await loadProjects()
      } catch (err) {
        console.error('强制刷新项目失败:', err)
      }
    }
  } catch (error) {
    console.error('初始化数据加载失败:', error)
  }
  
  // 如果URL中有项目ID参数，设置筛选并加载文件夹树
  if (route.query.project_id) {
    filterForm.project_id = route.query.project_id as string
    await loadFolders(filterForm.project_id)
  } else {
    // 如果没有项目ID，加载所有文件夹
    await loadFolders()
  }
  
  // 加载测试用例列表
  await loadTestCases()
  
  // 监听点击事件，关闭右键菜单
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped lang="scss">
.test-cases-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  
  .layout-container {
    display: flex;
    gap: 20px;
    flex: 1;
    overflow: hidden;
    min-height: 0;
    
    .left-panel {
      width: 320px;
      min-width: 280px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      
      .panel-card {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        
        :deep(.el-card__body) {
          flex: 1;
          overflow: hidden;
          display: flex;
          flex-direction: column;
        }
        
        .panel-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .panel-title {
            font-weight: 600;
            font-size: 16px;
          }
        }
        
        .folder-search {
          margin-bottom: 12px;
          flex-shrink: 0;
          
          :deep(.el-input__wrapper) {
            border-radius: 4px;
          }
        }
        
        .folder-tree-container {
          flex: 1;
          overflow-y: auto;
          overflow-x: hidden;
          min-height: 0;
          margin-bottom: 12px;
          
          :deep(.el-tree) {
            .tree-node {
              display: flex;
              align-items: center;
              flex: 1;
              width: 100%;
              padding-right: 8px;
              
              .node-label {
                flex: 1;
                display: flex;
                align-items: center;
                gap: 6px;
                min-width: 0;
                
                .node-icon {
                  color: #409EFF;
                  flex-shrink: 0;
                }
                
                span {
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }
              
              .node-count {
                color: #909399;
                font-size: 12px;
                margin-left: 4px;
                flex-shrink: 0;
              }
              
              .node-actions {
                margin-left: auto;
                display: none;
                flex-shrink: 0;
                opacity: 0;
                transition: opacity 0.2s;
                
                .action-btn {
                  padding: 4px;
                  color: #909399;
                  
                  &:hover {
                    color: #409EFF;
                  }
                }
              }
              
              &:hover .node-actions {
                display: block;
                opacity: 1;
              }
            }
            
            .el-tree-node__content {
              height: 36px;
              padding: 0 8px;
              border-radius: 4px;
              transition: background-color 0.2s;
            }
            
            .el-tree-node__content:hover {
              background-color: #f5f7fa;
            }
            
            .el-tree-node.is-current > .el-tree-node__content {
              background-color: #e6f7ff;
              color: #409EFF;
              font-weight: 500;
            }
            
            .el-tree-node__expand-icon {
              color: #909399;
              font-size: 14px;
            }
            
            .el-tree-node__expand-icon.is-leaf {
              color: transparent;
            }
          }
          
          .empty-state {
            padding: 40px 20px;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 200px;
            
            :deep(.el-empty__description) {
              margin-top: 12px;
              color: #909399;
              font-size: 14px;
            }
            
            .el-button {
              margin-top: 16px;
            }
          }
        }
        
        .folder-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 12px;
          border-top: 1px solid #EBEEF5;
          flex-shrink: 0;
          
          .el-button {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            
            &:first-child {
              margin-right: 8px;
            }
          }
        }
        
        // 拖拽样式
        .drag-over {
          background-color: #e6f7ff !important;
          border: 2px dashed #409EFF;
          border-radius: 4px;
        }
        
        .tree-node[draggable="true"] {
          cursor: move;
          
          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
    
    .right-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      min-width: 0;
    }
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .header-left {
      .page-title {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
      
      .page-description {
        margin: 0;
        font-size: 14px;
        color: #909399;
      }
    }
    
    .header-right {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
  
  .filter-section {
    margin-bottom: 20px;
    flex-shrink: 0;
    
    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .filter-left {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }
    
    .advanced-filter {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #EBEEF5;
    }
  }
  
  .table-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-height: 0;
    
    :deep(.el-card) {
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      
      .el-card__body {
        flex: 1;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        min-height: 0;
      }
    }
    
    :deep(.el-table) {
      flex: 1;
      overflow: auto;
    }
    
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
      flex-shrink: 0;
      padding: 0 20px 20px 0;
    }
  }
  
  // 时间列样式 - 内容靠上对齐
  :deep(.time-column) {
    .cell {
      padding-top: 8px !important;
      padding-bottom: 8px !important;
      display: flex;
      align-items: flex-start;
    }
  }
  
  .time-cell {
    line-height: 1.4;
    word-break: break-word;
  }
  
  .text-placeholder {
    color: #C0C4CC;
  }
}

// 右键菜单样式
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 3000;
  min-width: 160px;
  padding: 4px 0;
  
  .context-menu-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    cursor: pointer;
    font-size: 14px;
    color: #606266;
    
    &:hover {
      background-color: #f5f7fa;
      color: #409EFF;
    }
    
    .el-icon {
      font-size: 16px;
    }
  }
  
  .context-menu-divider {
    height: 1px;
    background-color: #e4e7ed;
    margin: 4px 0;
  }
}

// 测试用例行拖拽样式
.test-case-row {
  cursor: move;
  
  &:hover {
    opacity: 0.8;
  }
}
</style>



